const fs = require('fs').promises;

const express = require('express');
const app = express();
const port = 8080;
app.set("view engine","ejs");
app.set("views","./views");

const dicturl="http://www.eudic.cn";
//const datadir="D:/projs/cs/htmlwold/danci/danci/data";
const datadir ="D:/yu/projs/htmlwold/danci/danci/data";
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});


const path = require('path');
const httpProxy=require('http-proxy');
const proxy = httpProxy.createProxyServer();
app.all('/dicts/*', (req, res) => {
  proxy.web(req, res, { target: dicturl });
});

app.get('/', async (req, res) => {
  const stream = res.status(200).set('Content-Type', 'text/html');
  const files = await fs.readdir(datadir);
  res.render('index',{files:files});
  // files.forEach(element => {
  //       stream.write(`<h2><a href="/files/${element}"> ${element} </a></h2>`);    
  //   });
  // stream.end();
});

app.get('/files/:filename', async (req, res) => {
    
    const readline = require('readline');
    const filename = req.params.filename;
    const fullfilename= `${datadir}/${filename}`;
    
    
    const oStream = res.status(200).set('Content-Type', 'text/html');
    //res.sendFile(fullfilename);
    const s = await fs.readFile(fullfilename,'utf8');
    const words = s.split("\r\n");

    res.render('detail',{filename:filename,words:words});
    // words.forEach(item=>{
    //   oStream.write(`<span class="item">${item}</span> `);
    // })
    // oStream.end();
  });